import {
    msg,
    close,
    nextTick,
    open
} from '../../common/utils.js';
import Vue from 'vue';
import {
    serverPath,
    json,
    currentPath
} from '../../common/config.js';
import VoteService from '../services/votesService.js';

window.Module = function () {
    let voteService = new VoteService();
    return new Vue({
        el: '#addPageController',
        data: {
            entity: {
                votesDetails:[],
                Categorys:[]
            }
        },
        methods: {
            init: async function () {
            },
            add: async function () {
                if (!validator.checkAll('form')) {
                    layer.msg('请填写正确参数');
                    return;
                }
                var self = this;
                this.entity.categorys = [];
                _.forEach(this.entity.Categorys, function (value) {
                    self.entity.categorys.push(value.id);

                });
                let res = await voteService.createVotes(this.entity);
                if (!res.type) {
                    for (var item in res) {
                        msg(res[item][0]);
                        break;
                    }
                }
                else {
                    var response = res.body;
                    if ('Success' == response.result) {
                        this.close();
                    }
                    else {
                        msg(response.message);
                    }
                }
            },
            close: function () {
                close();
            },
            addDetails:async function(){
                this.entity.votesDetails.push({
                    sort:this.sort++
                });
                await nextTick();
                $(document)[0].dispatchEvent(new Event('icheck:render'));
            },
            deleteVotesDetails:async function(index){
                this.entity.votesDetails.splice(index,1);
                this.$forceUpdate();
            },
            addCategorys: async function () {
                let options = {
                    title: "选择分类",
                    content: `${currentPath}dialog.html#/TemplatePage/selectCategoryPage`,
                    maxmin: false,
                    area: ['80%', '70%']
                };
                await open(options);
                if (window.result) {
                    var index = _.findIndex(this.entity.Categorys, function (value) {
                        return value.id == window.result.id;
                    });
                    if (index < 0)
                        this.entity.Categorys.push(window.result);
                    delete window.result;
                    this.$forceUpdate();
                }
            },
            deleteCategory: function (index) {
                this.entity.Categorys.splice(index, 1);
                this.$forceUpdate();
            }
        }
    });
}